#!/bin/bash
# SPDX-License-Identifier: MulanPSL-2.0+
# Copyright (c) 2020 Huawei Technologies Co., Ltd. All rights reserved.

CONTAINER_PATH="$CCI_SRC/container"
export action=$1

source ${CCI_SRC}/lib/log.sh

build_depends()
{
	local container=$1

	for dep in $(cat $container/*-depends 2> /dev/null)
	do
		build_depends $CONTAINER_PATH/$dep &
	done
	wait

	do_one_build $container
}

do_one_build()
{
	local container=$1
	local container_name=$(basename $container)
	lockfile-create -q --use-pid --retry 100 --lock-name "$container_name".lock

	mkdir $tmpdir/$container_name 2>/dev/null &&
	(
		cd "$container"
		[ -x build ] && ./build
		[ "$?" == 0 ] && log_info "finish build $container"
		[ -x install ] && ./install
	)
	lockfile-remove --lock-name "$container_name".lock
}

start_depends()
{
	local container=$1

	for dep in $(cat $container/start-depends 2> /dev/null)
	do
		start_depends $CONTAINER_PATH/$dep
	done

	do_one_run $container
}

do_one_run()
{
	local container=$1
	local container_name=$(basename $container)

	mkdir $tmpdir/start_$container_name 2>/dev/null &&
	(
		cd "$container"
		[ "$container_name" == 'ssh-r' ] && continue
		[ -x first-run ] && ./first-run
		[ -x start ] && ./start
		[ "$container_name" == 'initrd-lkp' ] && ./run
	)
}

tmpdir=$(mktemp -d)

for dir in $CONTAINER_PATH/*/
do
	build_depends $dir
	start_depends $dir
done

rm -fr $tmpdir
